const nodepath = require('path')
const Nunjucks = require('nunjucks')
const { API_ROOT, STATIC_ROOT } = require('./config')

class Template {
  constructor(path = '/views', opts) {
    this.path = path
    this.path = nodepath.join(__dirname, this.path)
    this.noCache = opts.noCache || false
    this.watch = opts.watch || false
    this.autoescape = opts.autoescape || true
    this.throwOnUndefined = opts.throwOnUndefined || false
    this.filters = opts.filters
  }

  createNjk() {
    const env = new Nunjucks.Environment(
      new Nunjucks.FileSystemLoader(this.path, {
        noCache: this.noCache,
        watch: this.watch
      }),
      {
        autoescape: this.autoescape,
        throwOnUndefined: this.throwOnUndefined
      }
    )
    if (this.filters) {
      Object.keys(this.filters).forEach(k => {
        env.addFilter(k, this.filters[k])
      })
    }

    return env
  }

  addVariables(env) {
    env.addGlobal('API_ROOT', API_ROOT)
    env.addGlobal('STATIC_ROOT', STATIC_ROOT)
  }

  connect(app) {
    const env = this.createNjk()
    this.addVariables(env)
    app.context.render = function(view, model) {
      this.response.body = env.render(view, Object.assign({}, this.state || {}, model || {}))
      this.response.type = 'text/html'
    }
  }
}

module.exports = Template
